﻿using Dapper;
using System;
using BCEntity.Sim.Admin.AdminAuth;
using System.Collections.Generic;
using System.Data;
using System.Text;
using System.Threading.Tasks;
using BCCommon;
using BCCommon.Enums;

namespace BCData.Sim.Admin.AdminAuth
{
    /// <summary>
    /// 员工授权信息
    /// </summary>
    public class AdminAuthData : IAdminAuthData
    {
        private readonly IDatabaseContext databaseContext;
        private const string QUERY_EXISTS = @"SELECT 1 FROM adminauth";
        private const string QUERY = @"SELECT AdminAuthId,AdminId,AuthType,UnionId,AuthInfo FROM adminauth";
        public AdminAuthData(IDatabaseContext databaseContext)
        {
            this.databaseContext = databaseContext;
        }
        
        #region 检查员工授权信息是否存在
        public async Task<bool> Exists(long adminAuthId)
        {
            string sql = string.Format(@"{0} WHERE AdminAuthId=?AdminAuthId", QUERY_EXISTS);
            DynamicParameters parameters = new DynamicParameters();
            parameters.Add("?AdminAuthId", adminAuthId, DbType.Int64);
            return await this.databaseContext.Slave.ExecuteScalarAsync(sql, parameters) != null;
        }
        public async Task<bool> Exists(AuthType authType, string unionId)
        {
            string sql = string.Format(@"{0} WHERE AuthType=?AuthType AND UnionId=?UnionId", QUERY_EXISTS);
            DynamicParameters parameters = new DynamicParameters();
            parameters.Add("?AuthType", authType.ToString(), DbType.AnsiString);
            parameters.Add("?UnionId", unionId, DbType.AnsiString);
            return await this.databaseContext.Slave.ExecuteScalarAsync(sql, parameters) != null;
        }
        #endregion

        #region 添加员工授权信息
        public async Task<AdminAuthEntity> Add(AdminAuthEntity entity)
        {
            string sql = SqlCommands.GetInsertSql("adminauth", new string[] { "AdminId", "AuthType", "UnionId", "AuthInfo" });
            sql = string.Format("{0} {1} WHERE AdminAuthId=LAST_INSERT_ID();", sql, QUERY);
            DynamicParameters parameters = new DynamicParameters();
            parameters.Add("?AdminId", entity.AdminId, DbType.Int64, size: 20);
            parameters.Add("?AuthType", entity.AuthType.ToString(), DbType.AnsiString);
            parameters.Add("?UnionId", entity.UnionId?.Trim(), DbType.AnsiString, size: 50);
            parameters.Add("?AuthInfo", entity.AuthInfo?.Trim(), DbType.AnsiString, size: 1000);
            return await this.databaseContext.Master.QueryFirstOrDefaultAsync<AdminAuthEntity>(sql, parameters, databaseContext.Transaction);

        }
        #endregion

        #region 修改员工授权信息
        public async Task<AdminAuthEntity> Update(AdminAuthEntity entity)
        {
            string sql = SqlCommands.GetUpdateSql("adminauth", new string[] { "AdminId", "AuthType", "UnionId", "AuthInfo" }, new string[] { "AdminAuthId" });
            sql = string.Format("{0} {1} WHERE AdminAuthId=?AdminAuthId;", sql, QUERY);
            DynamicParameters parameters = new DynamicParameters();
            parameters.Add("?AdminAuthId", entity.AdminAuthId, DbType.Int64, size: 20);
            parameters.Add("?AdminId", entity.AdminId, DbType.Int64, size: 20);
            parameters.Add("?AuthType", entity.AuthType.ToString(), DbType.AnsiString);
            parameters.Add("?UnionId", entity.UnionId?.Trim(), DbType.AnsiString, size: 50);
            parameters.Add("?AuthInfo", entity.AuthInfo?.Trim(), DbType.AnsiString, size: 1000);
            return await this.databaseContext.Master.QueryFirstOrDefaultAsync<AdminAuthEntity>(sql, parameters, databaseContext.Transaction);
        }
        #endregion

        #region 删除员工授权信息
        public async Task<bool> Delete(long adminAuthId)
        {
            string sql = @"DELETE FROM adminauth WHERE AdminAuthId=?AdminAuthId";
            DynamicParameters parameters = new DynamicParameters();
            parameters.Add("?AdminAuthId", adminAuthId, DbType.Int64);
            return await this.databaseContext.Master.ExecuteAsync(sql, parameters, databaseContext.Transaction) > 0;
        }
        #endregion

        #region 获取员工授权信息
        public async Task<AdminAuthEntity> GetEntity(long adminAuthId)
        {
            string sql = string.Format(@"{0} WHERE AdminAuthId=?AdminAuthId", QUERY);
            DynamicParameters parameters = new DynamicParameters();
            parameters.Add("?AdminAuthId", adminAuthId, DbType.Int64);
            return await this.databaseContext.Slave.QueryFirstOrDefaultAsync<AdminAuthEntity>(sql, parameters);
        }

        public async Task<AdminAuthEntity> GetEntity(AuthType authType, string unionId)
        {
            string sql = string.Format(@"{0} WHERE AuthType=?AuthType AND UnionId=?UnionId LIMIT 1", QUERY);
            DynamicParameters parameters = new DynamicParameters();
            parameters.Add("?AuthType", authType.ToString(), DbType.AnsiString);
            parameters.Add("?UnionId", unionId, DbType.AnsiString);
            return await this.databaseContext.Slave.QueryFirstOrDefaultAsync<AdminAuthEntity>(sql, parameters);
        }
        #endregion

        #region 获取员工授权信息列表
        public async Task<IEnumerable<AdminAuthEntity>> GetList(long adminId)
        {
            string sql = string.Format(@"{0} WHERE AdminId=?AdminId", QUERY);
            DynamicParameters parameters = new DynamicParameters();
            parameters.Add("?AdminId", adminId, DbType.Int64);
            return await this.databaseContext.Slave.QueryAsync<AdminAuthEntity>(sql,parameters);
        }
        #endregion

        #region 获取员工授权信息分页
        public async Task<(IEnumerable<AdminAuthEntity>, int)> Query(DateTime? start, DateTime? end, string sortName, bool? ascending, int pageIndex, int pageSize)
        {
            List<string> wheres = new List<string>();
            DynamicParameters parameters = new DynamicParameters();

            if (start.HasValue && !end.HasValue)
            {
                wheres.Add("CreateTime>=?Start");
                parameters.Add("?Start", start.Value, DbType.DateTime);
            }
            else if (!start.HasValue && end.HasValue)
            {
                wheres.Add("CreateTime<=?End");
                parameters.Add("?End", end.Value, DbType.DateTime);
            }
            else if (start.HasValue && end.HasValue)
            {
                wheres.Add("CreateTime>=?Start AND CreateTime<=?End");
                parameters.Add("?Start", start.Value, DbType.DateTime);
                parameters.Add("?End", end.Value, DbType.DateTime);
            }
            string sql = string.Format(@"{0} {1} ORDER BY {4} {5} LIMIT {2},{3}; SELECT COUNT(1) FROM adminauth {1}",
                  QUERY,
                  wheres.Count > 0 ? " WHERE " + string.Join(" AND ", wheres) : "",
                  (pageIndex == 0 ? 0 : pageIndex - 1) * pageSize,
                  pageSize,
                  string.IsNullOrWhiteSpace(sortName) ? "AdminAuthId" : sortName,
                  ascending.HasValue && ascending.Value ? "ASC" : "DESC");
            return await this.databaseContext.Slave.QueryMultipleAsync<AdminAuthEntity, int>(sql, parameters);
        }
        #endregion
    }
}



